//app.js
//说明--小程序每次进来先执行的程序
// https://blog.csdn.net/caohoucheng/article/details/82012489
import cache from './utils/Cache.js';
import http from './utils/http.js';
import url from './utils/url.js';
App({
  onLaunch: function () {
    let openid = cache.has('openid');
    let token = cache.has('token');
    if(!token){
      this.getToken();
    }else{
      if (!openid) {
        this.getLoginInfo()
      }
    }
  },
  globalData: {
    userInfo: null
  },
  //登录获取token信息
  getToken:function(){
    var that = this;
    http.http(url.login,'POST',{username:'admin',password:'admin888'},function(res){
      if(res.token){
        //登录成功，已经获取到token
        //再去获取用户openid
        cache.setSorg('token','Bearer '+res.token)
        that.getLoginInfo();
      }
    });
  },
  //登录获取用户信息
  getLoginInfo:function(){
    wx.login({
      success(res) {
        if (res.code) {
          wx.request({
            url: url.wxlogin, //仅为示例，并非真实的接口地址
            data: {code:res.code},
            header: {
              'content-type': 'application/json', // 默认值
              'Authorization': cache.getSorg('token')
            },
            method: 'POST',
            success(res) {
              //获取到用户信息之后，对用户信息进行缓存
              cache.setSorg('openid',res.data.openid)
              wx.showToast({
                title: '登录成功',
              })
            }
          })
        } else {
          console.log('登录失败' + res.errMsg)
        }
      }
    })
  }
})